<template>
  <div class="container">
    <el-row class="toolbar searchInputWidth" style="padding-bottom: 0">
      <el-form :inline="true" :model="filterField" ref="searchConditions">
        <el-form-item label="是否签约" class="row-padding-bottom">
          <el-select
            v-model="filterField.signed"
            clearable
            placeholder="请选择"
          >
            <el-option label="已签约" value="1"></el-option>
            <el-option label="未签约" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否代发" class="row-padding-bottom">
          <el-select
            v-model="filterField.isUndertakes"
            clearable
            placeholder="请选择"
          >
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="icon iconfont iconchazhao1"
            @click="searchList"
            class="searchBtn"
          >
            <span>搜索</span>
          </el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <!-- 表格 -->
    <el-table
      :data="tableList"
      v-loading="loading"
      :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
      highlight-current-row
      stripe
      style="border: 1px solid #dfe6ec"
    >
      <el-table-column
        prop="bankName"
        label="统一专户开户行"
        align="center"
        :formatter="formatTd"
        min-width="160"
      ></el-table-column>
      <el-table-column
        prop="account"
        label="统一专户账号"
        align="center"
        :formatter="formatTd"
        min-width="200"
      ></el-table-column>
      <el-table-column
        prop="signedName"
        label="签约状态"
        align="center"
        :formatter="formatTd"
        min-width="110"
      ></el-table-column>
      <el-table-column
        prop="areaName"
        label="区域"
        align="center"
        :formatter="formatTd"
        min-width="110"
      ></el-table-column>
      <el-table-column
        prop="expensesTotal"
        label="总支出（元）"
        align="center"
        :formatter="formatTd"
        min-width="130"
      ></el-table-column>
      <el-table-column
        prop="balance"
        label="余额（元）"
        align="center"
        :formatter="formatTd"
        min-width="130"
      ></el-table-column>
      <el-table-column
        prop="numberStr"
        label="项目数(使用该专户的项目)"
        align="center"
        :formatter="formatTd"
        min-width="200"
      ></el-table-column>
      <el-table-column label="操作" align="left" fixed="right" min-width="160">
        <template slot-scope="scope">
          <el-link type="primary" @click="goOut(scope.row)">查看流水</el-link>
          <el-link type="primary" @click="editInfo(scope.row)">修改</el-link>
        </template>
      </el-table-column>
      <!-- 表格数据为空时，页面显示 -->
      <div slot="empty" v-show="isShow">
        <emptyTable emptyText="暂无相关信息"></emptyTable>
      </div>
    </el-table>
    <!-- 分页 -->
    <Pagination
      @getpageSize="getpageSize"
      @getpageNo="getpageNo"
      ref="pagination"
      @getList="getTableList"
      :filterField="filterField"
      :requestUrl="requestUrl"
    ></Pagination>
    <!-- 修改 -->
    <el-dialog
      title="修改工资专户信息"
      :visible="accountFormVisible"
      :close-on-click-modal="false"
      @close="cancelAccountDialog('accountForm')"
      width="640px"
      custom-class="brand-dialog-min-width accountDialog"
      :modal-append-to-body="false"
    >
      <p class="warningInfo">
        <i class="el-icon-warning warningIcon"></i>
        <span class="warningText"
          >请添加授权项目使用的统一专户，仅可使用本专户供多个项目使用。</span
        >
      </p>
      <p class="warningInfo" v-show="isShowErrorMsg">
        <i class="el-icon-warning warningIcon"></i>
        <span class="warningText">{{ errorMsg }}</span>
      </p>
      <div style="padding: 16px 20px">
        <el-form
          :model="accountForm"
          :rules="formRules"
          label-width="120px"
          class="mrT8"
          ref="accountForm"
        >
          <el-form-item label="区域：" prop="areaId">
            <el-cascader
              v-model="areaId"
              :options="areasOptions"
              class="dialogSingleInp"
              @change="getAreaId"
              :disabled="areaDisabled"
              clearable
              filterable
              placeholder="请选择"
              :props="{ checkStrictly: true }"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="开户银行：" prop="bankId">
            <el-select
              v-model="accountForm.bankId"
              placeholder="请选择"
              class="dialogSingleInp"
              clearable
              filterable
              :disabled="accountForm.projectTotal > 0 && bankInfo"
              @change="changeBankId"
            >
              <el-option
                v-for="(item, index) of bankOptions"
                :key="index"
                :label="item.name"
                :value="item.code"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="银行网点：" prop="bankSiteId">
            <el-select
              v-model="accountForm.bankSiteId"
              class="dialogSingleInp"
              :placeholder="
                accountForm.bankId != '' ? '请选择' : '请先选择开户银行'
              "
              clearable
              filterable
              :disabled="bankInfo"
            >
              <el-option
                v-for="(item, index) of bankBranchOptions"
                :key="index"
                :label="item.name"
                :value="item.code"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="专户账号：" prop="account">
            <el-input
              maxlength="64"
              v-model="accountForm.account"
              autocomplete="off"
              :disabled="bankInfo"
              placeholder="请输入专户账号"
              class="dialogSingleInp"
              @blur="accountForm.account = changeValue($event)"
            ></el-input>
          </el-form-item>
          <el-form-item label="专户开户凭证：">
            <uploadAnnex
              :limitationFactor="limitationFactor"
              @getFile="getFile"
              :upLoadFile="accountForm.upLoadFileAcc"
            />
          </el-form-item>
          <el-row>
            <el-col :span="24">
              <uploadResult
                style="margin-left: 116px !important"
                :resultList="accountForm.upLoadFileAcc"
                @callBackResult="getFile"
              />
            </el-col>
          </el-row>
          <el-form-item
            label="农民工工资委托发放三方协议："
            class="agreementBox"
          >
            <uploadAnnex
              :limitationFactor="limitationFactorAgr"
              @getFile="getFileAgr"
              :upLoadFile="accountForm.upLoadAgreementFile"
            />
          </el-form-item>
          <el-row>
            <el-col :span="24">
              <uploadResult
                style="margin-left: 116px !important"
                :resultList="accountForm.upLoadAgreementFile"
                @callBackResult="getFileAgr"
              />
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button
          @click.native="cancelAccountDialog('accountForm')"
          class="cancel"
          >取消</el-button
        >
        <el-button
          type="primary"
          @click.native="saveBankInfo('accountForm')"
          class="save"
          :loading="saveLoading"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapActions, mapState } from 'vuex'

export default {
  name: 'yiChangeEpecialAccountList',
  props: ['companyName', 'uscc'],
  data() {
    return {
      tableList: [],
      isShow: false, //列表加载
      loading: false,
      pageSize: 20,
      pageNo: 1,
      filterField: {
        companyName: '',
        uscc: '',
        signed: '',
        isUndertakes: '',
      },
      requestUrl: 'api-acc/companyaccount/expand/findaccountinfobyuscc',

      accountFormVisible: false,
      accountForm: {
        // projectId: "",
        id: '',
        areaId: '',
        bankId: '', //银行id
        bankSiteId: '', //银行网点id
        account: '', //专户号
        upLoadFileAcc: [], //开户凭证
        upLoadAgreementFile: [], //三方协议
      },
      areaId: '',
      bankOptions: [], //银行列表
      bankBranchOptions: [], //银行网点
      formRules: {
        areaId: [
          {
            required: true,
            message: '区域不能为空',
            trigger: 'change',
          },
        ],
        bankId: [
          {
            required: true,
            message: '银行不能为空',
            trigger: 'change',
          },
        ],
        bankSiteId: [
          {
            required: true,
            message: '银行网点不能为空',
            trigger: 'change',
          },
        ],
        account: [
          {
            required: true,
            // pattern: /^([1-9]{1})(\d{11,18})((-)(\d{1,9}))*$/,
            pattern: /^[^\u4e00-\u9fa5]{0,}$/,
            message: '请输入正确格式的账号',
            trigger: 'blur',
          },
        ],
      },
      saveLoading: false, //专户保存按钮loading
      limitationFactor: {
        uploadAnnexUrl: 'api-f/files/upload', //自定义上传文件接口地址
        upLoadFileLength: 10, //自定义上传文件最大数量设置
        fileSize: 5, //自定义上传文件最大设置
        formatType: 'typeFour', //自定义上传格式校验类型
        messagetip:
          '要求格式为png，jpg，jpeg，doc，docx，xls，xlsx，pdf格式，附件大小不超过5M', //自定义报错提示语
        fileId: 'salaryExcel', //自定义id解决一个页面包含多个上传附件
        uploadFormId: 'salaryExcelForm', //自定义id解决一个页面包含多个上传附件
        methodTip:
          '请上传专户开户凭证，附件格式支持png，jpg，jpeg，doc，docx，xls，xlsx，pdf，最多上传10个附件', //自定义上传文件提示
        uploadBtnType: 'typeOne', //自定义上传按钮类型
        messageFileSizetip: '最多能上传5M以内的附件',
      },
      limitationFactorAgr: {
        uploadAnnexUrl: 'api-f/files/upload', //自定义上传文件接口地址
        upLoadFileLength: 10, //自定义上传文件最大数量设置
        fileSize: 5, //自定义上传文件最大设置
        formatType: 'typeFour', //自定义上传格式校验类型
        messagetip:
          '要求格式为png，jpg，jpeg，doc，docx，xls，xlsx，pdf格式，附件大小不超过5M”', //自定义报错提示语
        fileId: 'salaryExcelAgr', //自定义id解决一个页面包含多个上传附件
        uploadFormId: 'ExcelAgreement', //自定义id解决一个页面包含多个上传附件
        methodTip:
          '请上传农民工工资委托发放三方协议，附件格式支持png，jpg，jpeg，doc，docx，xls，xlsx，pdf，最多上传10个附件', //自定义上传文件提示
        uploadBtnType: 'typeOne', //自定义上传按钮类型
        messageFileSizetip: '最多能上传5M以内的附件',
      },
      isShowErrorMsg: false,
      errorMsg: '',

      areaDisabled: false,
      bankInfo: false,
    }
  },
  created() {
    this.filterField.companyName = this.companyName
    this.filterField.uscc = this.uscc
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
    })
  },
  computed: { ...mapState(['areasOptions']) },
  mounted() {
    if (localStorage.getItem('loginType') === 'JC') {
      this.areaDisabled = true
    }
  },
  methods: {
    getRecordList(account) {
      this.axios
        .post('api-p/account/expand/findBankAccountInfo', { account })
        .then((res) => {
          if (res.data.hasError) {
            this.bankInfo = true
          }
        })
    },
    editInfo(item) {
      console.log(item)
      this.accountFormVisible = true
      this.errorMsg = ''
      this.isShowErrorMsg = false
      this.getAccountInfo(item.account, item.uscc)
      this.getBank()
      if (localStorage.getItem('loginType') === 'QY') {
        this.getRecordList(item.account)
      }
    },
    // //专户弹框取消
    cancelAccountDialog() {
      this.accountForm.upLoadFileAcc = []
      this.accountForm.upLoadAgreementFile = []
      this.accountForm.projectId = ''
      this.$refs.accountForm.resetFields()
      this.accountFormVisible = false
    },
    // 获取银行
    getBank() {
      var data = {
        type: 'BANK_TYPE',
      }
      return new Promise((resolve, reject) => {
        this.axios({
          method: 'post',
          url: 'api-bs/base/dicitem/findbytype',
          data: data,
        })
          .then((response) => {
            resolve(response)
            this.bankOptions = response.data.result
          })
          .catch((error) => {
            reject(error)
            this.$message.error('数据获取失败')
          })
      })
    },
    // 更改银行获取银行网点
    changeBankId(val) {
      this.accountForm.bankSiteId = ''
      if (!val) {
        this.bankBranchOptions = []
      } else {
        this.getBankBranchList(val)
      }
    },
    // 获取银行网点
    getBankBranchList(bankId) {
      return new Promise((resolve, reject) => {
        this.axios
          .post('api-acc/accountbank/expand/banksite', { bankId })
          .then((res) => {
            resolve(res)
            this.bankBranchOptions = res.data.result
            if (res.data.result.length === 0) {
              this.$message({
                message: '请联系银行管理员进行网点信息维护',
                type: 'warning',
              })
            }
          })
          .catch((error) => {
            reject(error)
            this.$message({
              message: '获取网点数据失败',
              type: 'error',
            })
          })
      })
    },
    // 修改专户带出专户信息
    getAccountInfo(account, uscc) {
      this.axios({
        method: 'post',
        url: 'api-acc/companyaccount/expand/findCompanyAccountInfo',
        data: {
          account,
          uscc,
        },
      })
        .then((res) => {
          if (!res.data.hasError) {
            let data = res.data.result
            this.accountForm = res.data.result
            // 子组件传值内容
            this.areaId = data.areaId
            this.accountForm.bankId = data.bankId
            this.accountForm.bankSiteId = data.bankSiteId
            this.accountForm.account = data.account
            this.accountForm.upLoadFileAcc = data.openCertificateFiles
            this.accountForm.upLoadAgreementFile = data.agreementFiles
            this.getBankBranchList(data.bankId)
          } else {
            this.$message({
              message: res.data.errorMsg,
              type: 'error',
            })
          }
        })
        .catch((error) => {
          this.$message.error('专户数据获取失败')
        })
    },
    getFile(val) {
      this.accountForm.upLoadFileAcc = val
    },
    getFileAgr(val) {
      this.accountForm.upLoadAgreementFile = val
    },
    getAreaId() {
      var areaId = this.areaId[this.areaId.length - 1]
      this.accountForm.areaId = areaId
    },
    //保存专户信息
    saveBankInfo(formName) {
      this.saveLoading = true
      //确定按钮禁止点击
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let data = {
            id: this.accountForm.id,
            areaId: this.accountForm.areaId,
            account: this.accountForm.account.replace(/\s+/g, ''),
            bankSiteId: this.accountForm.bankSiteId,
            bankId: this.accountForm.bankId,
            openCertificate: JSON.stringify(this.accountForm.upLoadFileAcc),
            agreement: JSON.stringify(this.accountForm.upLoadAgreementFile),
          }
          this.validAccountAjac(data)
        } else {
          this.saveLoading = false
          return false
        }
      })
    },
    validAccountAjac(data) {
      // var url = "api-acc/companyaccount/expand/addcompanyaccount";
      // var confirmUrl = "api-acc/companyaccount/expand/addcompanyaccountconfirm";

      // if(this.operationType === "updateAccount"){
      var url = 'api-acc/companyaccount/expand/updatecompanymanyaccount'
      var confirmUrl =
        'api-acc/companyaccount/expand/updatecompanyaccountconfirm'
      // }
      this.axios({
        method: 'post',
        url: url,
        data: data,
      })
        .then((res) => {
          this.saveLoading = false
          if (!res.data.hasError) {
            if (res.data.msgList && res.data.msgList.length > 0) {
              this.isShowErrorMsg = false
              this.$confirm(
                '企业中' +
                  res.data.msgList[0] +
                  '项目已绑定该专户，添加后将在企业统一专户中展示原有流水，项目端流水将被清空，是否确认？',
                '',
                {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning',
                }
              )
                .then(() => {
                  this.saveAccountAjax(confirmUrl, data)
                })
                .catch(() => {})
            } else {
              this.cancelAccountDialog() //关闭弹窗
              this.searchList()
            }
          } else {
            this.errorMsg = res.data.errorMsg
            this.isShowErrorMsg = true
          }
        })
        .catch((error) => {
          this.saveLoading = false
          this.$message({
            message: '请求失败',
            type: 'error',
          })
        })
    },
    //保存专户的ajax
    saveAccountAjax(url, data) {
      this.axios({
        method: 'post',
        url: url,
        data: data,
      })
        .then((res) => {
          this.saveLoading = false
          if (!res.data.hasError) {
            this.$message({
              message: '保存成功',
              type: 'success',
            })
            this.cancelAccountDialog() //关闭弹窗
            this.searchList()
          } else {
            this.$message({
              message: res.data.errorMsg,
              type: 'error',
            })
          }
        })
        .catch((error) => {
          this.saveLoading = false
          this.$message({
            message: '保存失败',
            type: 'error',
          })
        })
    },

    getpageSize(val) {
      this.pageSize = val
    },
    getpageNo(val) {
      this.pageNo = val
    },
    getTableList(data) {
      this.tableList = data
      this.loading = false
      if (this.tableList.length < 1) {
        this.isShow = true
      }
    },
    goOut(row) {
      this.$router.push({
        path: '/home/yiChangCustomRequirements/accountManageDetailFlow',
        name: 'accountManageDetailFlow',
        query: {
          account: row.account,
          id: row.id,
        },
      })
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/yiChangCustomRequirements/accountManageTab',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    // 搜索
    searchList() {
      this.$refs.pagination.getTableListData()
    },
  },
}
</script>

<style scoped lang="less">
.warningInfo {
  background: #fffbe6;
  height: 36px;
  padding-left: 46px;
  position: relative;
  .warningIcon {
    color: orange;
    font-size: 20px;
    position: absolute;
    top: 8px;
    left: 20px;
  }
  .warningText {
    font-family: 'SourceHanSansCN-Regular';
    font-size: 14px;
    color: #ff4d4a;
    line-height: 36px;
  }
}
/deep/ .el-dialog__body {
  padding: 0 !important;
}
// /deep/ .el-dialog__title {
//   font-family: SourceHanSansCN-Regular;
//   font-size: 18px;
//   color: #424242;
// }
.agreementBox {
  /deep/label {
    line-height: 20px;
  }
}
</style>
